import { Application } from 'egg';
import * as pageFindPlugin from 'mongoose-paginate';
import {
  CleanOrderStatus,
  OrderSource,
  CleanMemberOrderTypeEnums,
  CleanOrderStatusName,
  OrderSourceName } from '../constants';
import * as moment from 'moment';

/**
 * 保洁订单集合
 */
export default (app: Application) => {
  const mongoose = app.mongoose;
  const ObjectId = mongoose.Schema.Types.ObjectId;
  const cleanAppointmentOrderSchema = new mongoose.Schema({
    // 门店Id
    siteId: {
      type: ObjectId,
      required: true,
    },
    // 订单id
    orderId: {
      type: Number,
      required: true,
    },
    // 预约订单
    appointmentOrderId: {
      type: Object,
      required: false,
    },
    // 订单来源
    orderSource: {
      type: Number,
      default: OrderSource.client,
      enum: [ OrderSource.client, OrderSource.admin ],
      required: true,
    },
    // 订单类型
    orderType: {
      type: String,
      default: CleanMemberOrderTypeEnums.cleanOrder,
      required: true,
    },
    // 用户Id
    userId: {
      type: ObjectId,
      required: false,
    },
    // 服务开始时间
    serviceStartTime: {
      type: Date,
      required: true,
      get: (val: any) => moment(val).format('YYYY-MM-DD HH:mm'),
    },
    // 服务时长
    serviceTime: {
      type: Number,
      required: true,
    },
    // 用户姓名
    userName: String,
    // 电话号码
    phoneNumber: Number,
    // 服务门店
    siteName: String,
    // 详情地址
    address: String,
    // 服务产品Id
    productId: {
      type: ObjectId,
      required: true,
      ref: 'Cleanproduct',
    },
    // 服务保洁员Id
    cleanerId: ObjectId,
    // 服务保洁员名称
    cleanerName: String,
    // 评价星级分数
    evaluateScore: Number,
    // 评价描述
    evaluateDesc: String,
    // 状态
    status: {
      type: Number,
      default: CleanOrderStatus.unPaid,
      enum: CleanOrderStatus,
      required: true,
    },
    // 订单原价
    originalPrice: {
      type: Number,
      get: (val: any) => val / 100,
    },
    // 会员价
    membershipPrice: {
      type: Number,
      get: (val: any) => val / 100,
    },
    // 实际支付价格
    payPrice: {
      type: Number,
      get: (val: any) => val / 100,
    },
    // 支付时间
    payTime: {
      type: Date,
    },
  }, { toJSON: { virtuals: true, getters: true }, timestamps: true });

  // 状态描述
  // tslint:disable-next-line:ter-prefer-arrow-callback
  cleanAppointmentOrderSchema.virtual('statusName').get(function (this: any) {
    return CleanOrderStatusName[this.status];
  });

  // 状态描述
  // tslint:disable-next-line:ter-prefer-arrow-callback
  cleanAppointmentOrderSchema.virtual('orderSourceName').get(function (this: any) {
    return OrderSourceName[this.orderSource];
  });

  cleanAppointmentOrderSchema.index({ siteId: 1 });
  cleanAppointmentOrderSchema.plugin(pageFindPlugin, {});
  return mongoose.model('Cleanorder', cleanAppointmentOrderSchema);
};
